<?php

namespace app\api\logic;

use think\facade\Db;
use app\data\util\HttpUtil;
use think\exception\ValidateException;
use think\facade\Cache;

use app\order\logic\OrderSourceLogic;

class ApiOrdercheckLogic
{
    public function __construct()
    {

    }
    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 每月采购成本
     * @author zhangheng
     */
    public function MonthlySpuCost($params = [])
    {
        $where = [];

        $start_time = date('Y-m-01', strtotime('-1 month'));
        $end_time = date('Y-m-d 23:59:59', strtotime(-date('d') . 'day'));
        $where[]  = ['c.createtime', '>=', strtotime($start_time)];
        $where[]  = ['c.createtime', '<=', strtotime($end_time)]; 
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        
        $lists = Db::name('order_skuinfo')
            ->field('
                a.spu
            ')
            ->alias('a')
            ->join('qu_order_achievement c','a.order_id = c.order_id', 'left')
            ->where($where)
            ->group('a.spu')
            ->select()->toarray();

        //批量获取sku图片;
        $spus  = array_column($lists,'spu');

        //批量获取图片地址;
        $products     = Db::name('product_inventory')->field('spu,product_images')->whereIn('spu',$spus)->select()->toArray();
        $products_map = array_column($products,null,'spu');

        //批量获取图片地址;
        $ordercheck_spucost     = Db::name('ordercheck_spucost')->field('spu,material')->whereIn('spu',$spus)->order('timedate desc')->select()->toArray();
        $material_map = array_column($ordercheck_spucost,null,'spu');

        $date = date('Y-m', strtotime('-1 month'));
        $timedate = strtotime($date);
        foreach ($lists as $k=>$v) {
            $lists[$k]['date'] = $date;
            $lists[$k]['timedate'] = $timedate;
            $product_images = $products_map[$v['spu']]??[];
            $materials = $material_map[$v['spu']]??[];
            $lists[$k]['product_images'] = $product_images['product_images']??'';
            $lists[$k]['material'] = $materials['material']??'';
        }
        Db::name('ordercheck_spucost')->insertAll($lists);
        return json(DefaultResponse(200, true, '操作完成', '')); 
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 每月采购成本sku
     * @author zhangheng
     */
    public function MonthlySkuCost($params = [])
    {
        $where = [];

        $start_time = date('Y-m-01', strtotime('-1 month'));
        $end_time = date('Y-m-d 23:59:59', strtotime(-date('d') . 'day'));
        $where[]  = ['c.createtime', '>=', strtotime($start_time)];
        $where[]  = ['c.createtime', '<=', strtotime($end_time)]; 
        $where[]  = ['c.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];
        
        $date = date('Y-m', strtotime('-1 month'));
        $timedate = strtotime($date);
        $lists = Db::name('order_info')
            ->field('
                a.sku,a.spu,d.material,d.product_images
            ')
            ->alias('a')
            ->join('qu_order_achievement c','a.order_id = c.order_id', 'left')
            ->join('qu_ordercheck_spucost d','d.spu = a.spu', 'left')
            ->where($where)
            ->where('d.date', '=', $date)
            ->where('a.sku',"<>","")
            ->group('a.sku')
            ->select()->toarray();
        
        foreach ($lists as $k=>$v) {
            $lists[$k]['date'] = $date;
            $lists[$k]['timedate'] = $timedate;
            
            $count = $this->CountTheNumberOfItems($v);
            $lists[$k]['count'] = $count;
            $lists[$k]['material_total'] = (float)number_format((float)$v['material'] * $count, 3, '.', '');
        }
        Db::name('ordercheck_skucost')->insertAll($lists);
        return json(DefaultResponse(200, true, '操作完成', '')); 
    }

    /**
    * 统计sku
    * @param array params
    */
    public function CountTheNumberOfItems($arr_info)
    {
        $Number = 0;
        $sku = $arr_info['sku'];
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                //数量
                $km = count($sku) - 1;
                $numeric = is_numeric($sku[$km]) ? true : false;
                $Number = 1;
                if($numeric && $sku[$km] < 25){
                    //是数字并且小于100才计算数量
                    $Number = $sku[$km];
                }
                
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    $kmPlus = count($skuPlus);
                    if($kmPlus >= 1){
                        $Number = $Number * $kmPlus;
                    }
                }
            }
        }
        return $Number;
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 每月统计店铺业绩
     * @author zhangheng
     */
    public function MonthlyStatisticsOfStore($params = [])
    {
        $where = [];

        $start_time = date('Y-m-01', strtotime('-1 month'));
        $end_time = date('Y-m-d 23:59:59', strtotime(-date('d') . 'day'));
        $where[]  = ['a.createtime', '>=', strtotime($start_time)];
        $where[]  = ['a.createtime', '<=', strtotime($end_time)]; 
        $where[]  = ['a.financial_status', 'in', ["partially_paid", "paid", "partially_refunded", "refunded"]];

        $date = date('Y-m', strtotime('-1 month'));
        $timedate = strtotime($date);
        //汇率
        $order_exchange = Db::name('order_exchange')
            ->where(['date' => $date])
            ->find();

        $lists = Db::name('order_achievement')
            ->field('
                sum(a.freight) as freight,
                sum(a.material) as material,
                sum(a.dispute) as dispute,
                sum(a.total_price) as total_price,
                sum(a.skuquantity) as skuquantity,
                sum(a.refund) as refund,
                a.shop_id,
                b.name as shop_name
            ')
            ->alias('a')
            ->join('qu_shops b','b.id = a.shop_id', 'left')
            ->where($where)
            ->group('a.shop_id')
            ->select()->toarray();
            // halt($lists);
        foreach ($lists as &$v) { 
            $v['date'] = $date;
            $v['timedate'] = $timedate;
            $v['dollar'] = $order_exchange['dollar'] ?? 0;
            $order_exchange['LogisticsMarkupFee'] = $order_exchange['LogisticsMarkupFee'] ?? 0;
            $v['LogisticsMarkupFee'] = (float)number_format((float)$order_exchange['LogisticsMarkupFee'] / $order_exchange['dollar'], 3, '.', '');;
            //物流--人民币转美金
            $v['freight'] = (float)number_format((float)$v['freight'] / $order_exchange['dollar'], 3, '.', '');
            //采购
            $v['material'] = (float)number_format((float)$v['material'] / $order_exchange['dollar'], 3, '.', '');
            //TODO广告
            $v['advertising'] = 0;
            //TODO利润
            // $v['profit'] = (float)number_format((float)$v['total_price'] - $v['freight'] - $v['material'] - $v['LogisticsMarkupFee'] - $v['advertising'], 3, '.', '');  
        }
        Db::name('report_monthly_profit')
            ->where('date',$date)
            ->delete();
        Db::name('report_monthly_profit')->insertAll($lists);
        return json(DefaultResponse(200, true, '操作完成', '')); 
    }

    /**
    * @desc    实时记录今天业绩
    * @date    2024/7/16
    * @author  zhangheng
    */
    public function SplitSkuAndThenRestructure($sku = "")
    {
        $return = [];
        if(!empty($sku)){
            $pos = strpos($sku, '-');
            if($pos !== false){
                $sku = explode('-',$sku);
                $possku = strpos($sku[1], '+');
                if($possku !== false){
                    $skuPlus = explode('+',$sku[1]);
                    //存入到sku明细中---开始
                    foreach ($skuPlus as $kp=>$vp) {
                        $newsku = $sku[0].'-'.$vp.'-'.$sku[2];
                        if(!isset($return[$newsku])){
                            $return[$newsku] = 1;
                        }else{
                            $return[$newsku] += 1;
                        }
                    }
                }else{
                    $newsku = $sku[0].'-'.$sku[1].'-'.$sku[2];
                    if(!isset($return[$newsku])){
                        $return[$newsku] = 1;
                    }else{
                        $return[$newsku] += 1;
                    }
                }
            }
        }
        $return_new = [];
        if(empty($return)){
            return $return;
        }
        foreach ($return as $k=>$v) {
            if($v > 1){
                $return_new[] = $k."-".$v;
            }else{
                $return_new[] = $k;
            }
        }
        return $return_new;
    }
    
}
